import React, { Component } from 'react'
import { smsTemplateUploadUrl, smsTemplateDownloadUrl, smsTemplateGroupUploadUrl, smsTemplateGroupDownloadUrl } from '@/utils/settings.js'
import EnterpriseGroupView from '../../components/sms/telGroup/Enterprise'
import PersonalGroupView from '../../components/sms/telGroup/Personal'

import Enterprise from '../../components/sms/telBook/Enterprise'
import Personal from '../../components/sms/telBook/Personal'

import SmsList from '../../components/sms/SmsList'
import SendSmsView from '../../components/sms/SendSms'

import ImportView from '../../components/sms/Import'
import LinkStateView from '../../components/LinkState'
import styles from './sendSms.less'
import {
    Upload, message, Button, Icon, Divider, Switch
} from 'antd';

import { connect } from 'dva'

@connect(({ sms, loading }) => ({ 
  sendList: sms.sendList,
}))
export default class SendSms extends Component {

    constructor(props){
      super(props);
      this.state = {
        fileList:[], //点对点上传文件集合
        fileGroupList:[], //群发上传文件集合
        isPersonal: true,
      };
    }

    onFileGroupChange(info) {
      let {fileList} = info;
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      console.log(info)
      if (info.file.status === 'done') {
        if(info.file.response.success){
          message.success(`${info.file.name} 上传成功`);
          //设置导入的短信发送模板到弹出框
          const { dispatch } = this.props
          console.log("囧囧有神",info.file.response.data)
          dispatch({
              type: 'smsImport/setGroupShow',
              payload: {
                smsGroup: info.file.response.data,
                isGroupShow: true
              }
          })

        }else{
          message.error(`${info.file.name} 上传失败`);
        }
        fileList = []
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
      }
      this.setState({ fileGroupList: fileList });
    }

    onFileChange(info) {
      let {fileList} = info;
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        if(info.file.response.success){
          message.success(`${info.file.name} 上传成功`);
          //设置导入的短信发送模板到弹出框
          const { dispatch } = this.props
          console.log("囧囧有神",info.file.response.data)
          dispatch({
              type: 'smsImport/setShow',
              payload: {
                list: info.file.response.data,
                isShow: true
              }
          })

        }else{
          message.error(`${info.file.name} 上传失败`);
        }
        fileList = []
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
      }
      this.setState({ fileList: fileList });
    }

    addSendListHandInp = (handInpList)=> {
      console.log("----------",handInpList)
      const {sendList, dispatch} = this.props
      //手动输入
      const sendListTemp = JSON.parse(JSON.stringify(sendList))
      for(let i = 0; i < handInpList.length; i++){
        if(sendList.length > 0){
          let isOk = true
          for(let j = 0; j < sendList.length; j++){
            if(sendList[j].node.phone === handInpList[i].node.phone){
              isOk = false
            }
          }
          if(isOk){
            sendListTemp.push(handInpList[i])
          }
        }else{
          sendListTemp.push(handInpList[i])
        }
      }
      console.log("结果",sendListTemp)
      dispatch({
        type: 'sms/setSendList',
        payload: sendListTemp
      })
    }

    addSendList = (e)=> {
      console.log(e)
      const {sendList, dispatch} = this.props
      //判断重复
      let isSame = false 
      sendList.forEach(element => {
        if(element.type === e.type && element.node.id === e.node.id){
          isSame = true
        }
      });
      if(isSame){
        message.error(`${e.node.name} 已添加，请不要重复添加`);
        return
      }
      //分组
      if(e.type === "group"){
        const rs = {id: e.node.id, state: false, superName: null}
        sendList.forEach(element => {
          this.recursionGroup(element.node, rs)
        });
        if(rs.state){
          message.error(` 已添加 ${e.node.name} 的父级分组，无需重复添加子分组`);
          return
        }
      }
      //通讯录
      if(e.type === "telBook"){
        const rs = {id: e.node.groupId, state: false, superName: null}
        sendList.forEach(element => {
          this.recursionGroup(element.node, rs)
        });
        if(rs.state){
          message.error(` 已添加 ${e.node.name} 所属的分组，无需重复添加电话号`);
          return
        }
      }

      const sendListTemp = JSON.parse(JSON.stringify(sendList))
      if(e.type === "group"){
        //递归删除子分组
        this.recursionGroupDel(e, sendListTemp)
        //递归删除分组内的包含的通讯录
        this.recursionTelBookDel(e, sendListTemp)
      }
      sendListTemp.push(e)
      //排除sendList在删除后的所有undefined元素
      const lastSendList = sendListTemp.filter(e=> e !== undefined)
      dispatch({
            type: 'sms/setSendList',
            payload: lastSendList
      })
    }

    //递归查询分组所有子节点
    recursionGroup = (groupNode, rs) =>{
      //通讯录分组 id 等于遍历分组节点id PS：分组包含此电话号
      //console.log(groupNode.id, "---------", rs.id)
      if(groupNode.id === rs.id){
        rs.state = true
        rs.superName = groupNode.name
        return 
      }
      //判断是否是子分组
      if(groupNode.children && groupNode.children.length > 0){
        groupNode.children.map(item =>{
          //console.log(item.id,"=========",rs.id)
          if(item.id === rs.id){
            rs.state = true
            rs.superName = groupNode.name
            return 
          }
          this.recursionGroup(item, rs)
        })
      }
    }

    //递归删除分组内的包含的通讯录
    recursionTelBookDel = (group, sendList) =>{
      //通讯录分组 id 等于分组，删除通讯录
      sendList.map((temp,index) =>{
        if(temp){
          //判断是否输入某个分组， 是就删除
          if(temp.type === "telBook" && temp.node.groupId === group.node.id){
            delete sendList[index]
          }
          if(group.node.children && group.node.children.length > 0){
            //获取分组中的子分组继续迭代
            group.node.children.map(temp => {
              const node = {type:"group",node:temp}
              this.recursionTelBookDel(node, sendList)
            })
          }
        }
      })
    }

    //递归删除子分组
    recursionGroupDel = (superGroup, sendList) =>{
      sendList.map((temp,index) =>{
        if(temp){
          //判断是否输入某个分组， 是就删除
          if(temp.type === "group" && temp.node.superId === superGroup.node.id){
            delete sendList[index]
          }
          if(temp.type === "group" && temp.node.children && temp.node.children.length > 0){
            //把包含的分组子节点包装成发送列表迭代
            const childrenList = []
            temp.node.children.map(temp => {
              const node = {type:"group",node:temp}
              childrenList.push(node)
            })
            this.recursionTelBookDel(superGroup, childrenList)
          }
        }
      })
    }

    render() {
        console.log("发送渲染")
        console.log(this.props.sendList)
        const { sendList, dispatch } = this.props
        const { isPersonal } = this.state
        return (
            <div className = {styles.sendSmsContent}>
                <div className = {styles.left}>
                    <LinkStateView />
                    <div className = {styles.smsList}>
                        <SmsList {...this.props} addSendListFunc = {this.addSendListHandInp}/>
                    </div>
                    <Divider/>
                    <SendSmsView sendList = { sendList } dispatch = { dispatch }/>
                </div>
                <div className = {styles.right}>
                    <div className = {styles.header}>
                        <div className = {styles.up}>
                          <Switch checkedChildren="个人通信录" unCheckedChildren="企业通信录" defaultChecked onChange={(e)=>{
                              this.setState({
                                isPersonal: e
                              })
                            }}/>
                        </div>
                        <div className = {styles.down}>
                            <Button onClick = {()=>{
                                window.location.href = smsTemplateDownloadUrl
                              }}>
                              <Icon type="download" /> 点对点发送模板
                            </Button>
                          <Upload 
                            fileList={this.state.fileList} 
                            action={smsTemplateUploadUrl} 
                            name={"file"} 
                            onChange={this.onFileChange.bind(this)}>
                              <Button>
                              <Icon type="upload" /> 点对点发送
                              </Button>
                          </Upload>
                        </div>
                        <div className = {styles.down}>
                            <Button onClick = {()=>{
                                window.location.href = smsTemplateGroupDownloadUrl
                              }}>
                              <Icon type="download" /> 群发送模板
                            </Button>
                          <Upload 
                            fileList={this.state.fileGroupList} 
                            action={smsTemplateGroupUploadUrl} 
                            name={"file"} 
                            onChange={this.onFileGroupChange.bind(this)}>
                              <Button>
                              <Icon type="upload" /> 群发送
                              </Button>
                          </Upload>
                        </div>
                    </div>
                    <div className = {styles.body}>
                      { isPersonal ?
                        <PersonalGroupView addSendListFunc = {this.addSendList}/>
                        :
                        <EnterpriseGroupView addSendListFunc = {this.addSendList}/>
                      }
                    </div>
                    <div className = {styles.telBook}>
                    { isPersonal ?
                      <Personal addSendListFunc = {this.addSendList}/>
                      :
                      <Enterprise addSendListFunc = {this.addSendList}/>
                    }
                    </div>
                </div>
                <ImportView/>
            </div>
        )
    }
}
